package com.binance.notification.web.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import com.binance.distcache.distlock.DistLockManager;
import com.binance.distcache.distlock.IDistLock;
import com.binance.master.error.ErrorCode;
import com.binance.master.error.GeneralCode;
import com.binance.master.utils.DateUtils;
import com.binance.notification.web.utils.Constants;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.SerializationUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.binance.autojob.annotation.MyScheduledJob;
import com.binance.master.error.BusinessException;
import com.binance.notification.api.push.PushCommand;
import com.binance.notification.api.push.notification.AndroidPayload;
import com.binance.notification.api.push.notification.AppPayload;
import com.binance.notification.api.push.notification.IosPayload;
import com.binance.notification.api.push.notification.MultipleNotificationPacket;
import com.binance.notification.api.push.notification.PcPayload;
import com.binance.notification.api.push.notification.WebPayload;
import com.binance.notification.api.request.LongIdRequest;
import com.binance.notification.api.request.MessagePushRequest;
import com.binance.notification.api.request.MessageTypeRequest;
import com.binance.notification.api.request.MessageUpdateRequest;
import com.binance.notification.api.response.MessagePushBodyPageResponse;
import com.binance.notification.api.response.MessagePushPageResponse;
import com.binance.notification.api.response.MessageTypePageResponse;
import com.binance.notification.api.response.MessageTypeResponse;
import com.binance.notification.api.vo.MessagePushDetailVo;
import com.binance.notification.api.vo.MessagePushVo;
import com.binance.notification.api.vo.MessageTypeVo;
import com.binance.notification.data.mapper.MessagePushBodyMapper;
import com.binance.notification.data.mapper.MessagePushMapper;
import com.binance.notification.data.mapper.MessageTypeMapper;
import com.binance.notification.data.models.MessagePush;
import com.binance.notification.data.models.MessagePushBody;
import com.binance.notification.data.models.MessageType;
import com.binance.notification.web.push.Callback;
import com.binance.notification.web.service.IDeviceService;
import com.binance.notification.web.service.IMessagePushService;
import com.binance.notification.web.service.IPushService;
import com.binance.notification.web.service.abnormaltrade.log.LoggerUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lufei
 * @date 2018/11/2
 */
@Service
@Slf4j
public class MessagePushServiceImpl implements IMessagePushService {

    @Resource
    private MessageTypeMapper mtMapper;
    @Resource
    private MessagePushMapper pushMapper;
    @Resource
    private MessagePushBodyMapper pushBodyMapper;
    @Autowired
    private IDeviceService deviceService;
    @Resource
    private IPushService push;

    private org.slf4j.Logger logger = LoggerUtils.getLogger(MessagePushServiceImpl.class);
    @Autowired
    private DistLockManager distLockManager;
    private static final String MESSAGE_MODEL_ID_KEY = "messagePushId";

    // private ScheduledExecutorService scheduleService =
    // Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors() + 1);
    //
    // private Map<Long, ScheduledFuture<?>> futures = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {

    }

    @Override
    public void addType(MessageTypeRequest request) {
        Long total = this.mtMapper.checkUnique(request.getName());
        if (total > 0L) {
            log.info("消息推送，已经存在相同名称[{}]的类型", request.getName());
            throw new BusinessException("已经存在相同名称的类型");
        }
        MessageType mt = new MessageType();
        BeanUtils.copyProperties(request, mt);
        mt.setStatus(0);
        mt.setCreateTime(new Date());
        mtMapper.save(mt);
    }

    @Override
    public void updateType(MessageTypeRequest request) {
        MessageType mt = mtMapper.getById(request.getId());
        if (mt == null) {
            log.info("消息推送，主体[ID:{}]不存在数据", request.getId());
            throw new BusinessException("不存在数据");
        }
        Long total = this.mtMapper.checkUnique(request.getName());
        if (total > 0L) {
            log.info("消息推送，主体[ID:{},{}]已经存在相同名称的类型", request.getId(), request.getName());
            throw new BusinessException("已经存在相同名称的类型");
        }
        mt.setName(request.getName());
        mtMapper.update(mt);
    }

    @Override
    public void deleteType(LongIdRequest request) {
        mtMapper.delete(request.getId());
        log.info("消息推送，主体[ID:{}]已删除", request.getId());
    }

    @Override
    public MessageTypeResponse getTypeById(LongIdRequest request) {
        MessageType mt = mtMapper.getById(request.getId());
        if (mt == null) {
            log.info("消息推送，主体[ID:{}]不存在数据", request.getId());
            throw new BusinessException("不存在数据");
        }
        MessageTypeVo vo = new MessageTypeVo();
        BeanUtils.copyProperties(mt, vo);
        return new MessageTypeResponse(vo);
    }

    @Override
    public MessageTypePageResponse getTypeList(MessageTypeRequest request) {
        MessageType mt = new MessageType();
        BeanUtils.copyProperties(request, mt);
        List<MessageType> list = mtMapper.select(mt, request.getOffset(), request.getLimit());
        List<MessageTypeVo> rows = list.stream().map(e -> {
            MessageTypeVo vo = new MessageTypeVo();
            BeanUtils.copyProperties(e, vo);
            return vo;
        }).collect(Collectors.toList());
        Long total = mtMapper.selectCount(mt);
        return new MessageTypePageResponse(rows, total);
    }

    @Override
    public void saveOrUpdateMessagePush(MessagePushRequest request) {
        this.checkMessagePushRequest(request);
        MessagePushVo vo = request.getVo();
        MessagePush mp = new MessagePush();
        BeanUtils.copyProperties(vo, mp);

        List<MessagePushDetailVo> vos = request.getDetailVos();
        List<MessagePushBody> bodies = new ArrayList<>(vos.size());
        for (MessagePushDetailVo detailVo : vos) {
            MessagePushBody mpb = new MessagePushBody();
            BeanUtils.copyProperties(detailVo, mpb);
            bodies.add(mpb);
        }
        Long messageId = vo.getId();
        if (vo.getId() == null) {
            this.save(mp, bodies);
            messageId = mp.getId();
        } else {
            this.update(vo, bodies, request.getIsAudit(), request.getDeleteBodyIds());
        }
    }

    @Override
    public MessagePushVo getById(LongIdRequest request) {
        MessagePush mp = pushMapper.getById(request.getId());
        MessagePushVo vo = new MessagePushVo();
        BeanUtils.copyProperties(mp, vo);
        return vo;
    }

    @Override
    public MessagePushPageResponse getList(Long id, Long type, String remark, Integer status, Integer offset,
            Integer rows) {
        Map<String, Object> param = new HashMap<>();
        if (id != null) {
            param.put("id", id);
        }
        if (type != null) {
            param.put("type", type);
        }
        if (StringUtils.isNotBlank(remark)) {
            param.put("remark", remark);
        }
        if (status != null && status != 0) {
            param.put("statusList", Lists.newArrayList(status));
        }
        param.put("offset", offset);
        param.put("rows", rows);
        List<MessagePush> mps = pushMapper.selectByCondition(param);
        Long total = pushMapper.selectCountByCondition(param);
        List<MessagePushVo> list = new ArrayList<>(mps.size());
        for (MessagePush mp : mps) {
            MessagePushVo vo = new MessagePushVo();
            BeanUtils.copyProperties(mp, vo);
            list.add(vo);
        }
        return new MessagePushPageResponse(list, total);
    }

    @Override
    public MessagePushBodyPageResponse getMessagePushBodyList(LongIdRequest request) {
        List<MessagePushBody> bodies = pushBodyMapper.selectByMessageId(request.getId());
        if (CollectionUtils.isEmpty(bodies)) {
            return new MessagePushBodyPageResponse(Collections.emptyList(), 0L);
        }
        List<MessagePushDetailVo> vos = new ArrayList<>(bodies.size());
        for (MessagePushBody body : bodies) {
            MessagePushDetailVo vo = new MessagePushDetailVo();
            BeanUtils.copyProperties(body, vo);
            vos.add(vo);
        }
        return new MessagePushBodyPageResponse(vos, (long) vos.size());
    }

    @Override
    public void refuseNotice(MessageUpdateRequest request) {
        MessagePush mp = pushMapper.getById(request.getId());
        if (mp == null || mp.getStatus() != 1) {
            log.info("消息推送，主体[ID:{}]当前状态不是待审核或空", request.getId());
            throw new BusinessException("当前状态不是待审核，不能进行该操作");
        }
        if (StringUtils.equals(mp.getCreator(), request.getCreator())) {
            log.info("消息推送，主体[ID:{},adminId:{}]自己创建的自己不能审核", request.getId(), request.getCreator());
            throw new BusinessException("自己创建的自己不能审核哦");
        }
        mp.setStatus(4);
        pushMapper.update(mp);
    }

    @Override
    public void delete(LongIdRequest request) {
        MessagePush mp = pushMapper.getById(request.getId());
        if (mp == null) {
            throw new BusinessException("记录为空");
        }
        if (mp.getStatus() != 1 && mp.getStatus() != 2) {
            throw new BusinessException("记录状态不是\"待审核\"或\"未发送\"，不能删除");
        }
        mp.setStatus(5);
        pushMapper.update(mp);
    }

    @MyScheduledJob(cron = "0/5 * * * * ?", author = "wangxiao", alarmEmail = "louis.wang@binance.com",
            jobDesc = "5s轮询一次推送定时消息")
    public void timedPush() {
        Map<String, Object> param = Maps.newHashMap();
        param.put("statusList", Lists.newArrayList(1, 2));
        param.put("pushType", "fixed");
        param.put("sendTimeEnd", DateUtils.getNewUTCDate());
        List<MessagePush> result = pushMapper.selectByCondition(param);
        if (result != null) {
            for (MessagePush model : result) {
                if (model != null) {
                    logger.info("消息推送，定时推送任务开始执行[{}]", model.getId());
                    if (model.getStatus() == 1) {
                        logger.info("消息推送，定时推送任务执行中[{}]，发现状态是{}，因此作废。", model.getId(), model.getStatus());
                        model.setStatus(4);
                        pushMapper.update(model);
                        continue;
                    }
                    if (model.getStatus() != 2) {
                        logger.info("消息推送，定时推送任务执行中[{}]，发现状态{}不是未发送，因此将不做任何动作。", model.getId(), model.getStatus());
                        continue;
                    }
                    push(model.getId(), null, true);
                }
            }
        }
    }

    @Override
    public void send(MessageUpdateRequest request) {
        Map<String, Object> resultMap = this.push(request.getId(), request.getCreator(), false);
        boolean success = (boolean) resultMap.get("success");
        if (!success) {
            throw new BusinessException((String) resultMap.get("msg"));
        }
    }

    private void checkMessagePushRequest(MessagePushRequest request) {
        boolean en = false;
        MessagePushVo vo = request.getVo();
        if ("fixed".equals(vo.getPushType())) {
            if (vo.getSendTime() == null) {
                throw new BusinessException("定时推送时必须指定时间！");
            }
        }
        if (vo.getHoldonHours() != null) {
            if (vo.getHoldonHours() <= 0) {
                throw new BusinessException("离线保存时间必须是大于0的整数");
            }
        }
        String action = null;
        if (StringUtils.contains(vo.getChannel(), "b")) {
            action = vo.getAppActivity();
            if ("openAppIn".equals(action)) {
                if (StringUtils.isBlank(vo.getOpenAppInUrl())) {
                    throw new BusinessException("打开App内界面时必须填写界面地址");
                }
            }
            if ("openAppLink".equals(action)) {
                if (StringUtils.isBlank(vo.getOpenAppLinkCn()) || StringUtils.isBlank(vo.getOpenAppLinkEn())) {
                    throw new BusinessException("打开网址链接时必须填写链接地址");
                }
            }
        } else if (StringUtils.contains(vo.getChannel(), "c")) {
            action = vo.getPcActivity();
            if ("openPcLink".equals(action)) {
                if (StringUtils.isBlank(vo.getOpenPcWebCn()) || StringUtils.isBlank(vo.getOpenPcWebEn())) {
                    throw new BusinessException("打开网页页面时必须填写页面地址");
                }
            }
            if ("openPcIn".equals(action)) {
                if (StringUtils.isBlank(vo.getOpenPcAppUrl())) {
                    throw new BusinessException("打开应用内界面时必须填写界面地址");
                }
            }
        } else if (StringUtils.contains(vo.getChannel(), "d")) {
            action = vo.getWebActivity();
            if ("openWebLink".equals(action)) {
                if (StringUtils.isBlank(vo.getOpenWebUrlCn()) || StringUtils.isBlank(vo.getOpenWebUrlEn())) {
                    throw new BusinessException("打开网页页面时必须填写页面地址");
                }
            }
        }

        Set<String> set = new HashSet<>();
        List<MessagePushDetailVo> detailVos = request.getDetailVos();
        if (detailVos == null) {
            throw new BusinessException("需要语境通知内容");
        }
        for (MessagePushDetailVo body : detailVos) {
            if (set.contains(body.getLanguage())) {
                throw new BusinessException("只能有一条语言代码为" + body.getLanguage() + "的内容！");
            }
            set.add(body.getLanguage());
            if (StringUtils.equalsIgnoreCase(body.getLanguage(), "en")) {
                en = true;
                break;
            }
        }
        if (!en) {
            throw new BusinessException("必须填写语言代码为“en”的内容！");
        }
    }

    private void save(MessagePush pm, List<MessagePushBody> bodies) {
        pushMapper.save(pm);
        for (MessagePushBody body : bodies) {
            body.setMessageId(pm.getId());
            body.setCreator(pm.getCreator());
            pushBodyMapper.save(body);
        }
    }

    private void update(MessagePushVo vo, List<MessagePushBody> bodies, Boolean isAudit, List<Long> deleteBodyIds) {
        MessagePush model = pushMapper.getById(vo.getId());
        if (model == null || model.getStatus() != 1) {
            log.info("消息推送，主体[ID:{}]当前状态不是待审核或空", vo.getId());
            throw new BusinessException("当前状态不是待审核，不能进行该操作！");
        }
        MessagePush mp = new MessagePush();
        BeanUtils.copyProperties(vo, mp);
        if (vo.getUsers() == null) {// 用户没有上传Exl
            mp.setUsers(model.getUsers());
        }
        mp.setStatus(model.getStatus());
        if (isAudit != null && isAudit.booleanValue()) {
            if (StringUtils.equals(model.getCreator(), vo.getCreator())) {
                log.info("消息推送，主体[ID:{},adminId:{}]自己创建的自己不能审核", model.getId(), vo.getCreator());
                throw new BusinessException("自己创建的自己不能审核哦");
            }
            mp.setStatus(2);
        }
        if (mp.getStatus() != 1 && mp.getStatus() != 2) {
            log.info("消息推送，主体[ID:{},{}]当前通知记录的状态不是待审核、未发送，不能修改", model.getId(), mp.getStatus());
            throw new BusinessException("当前通知记录的状态不是\"待审核\"或\"未发送\"，不能修改");
        }
        pushMapper.update(mp);
        for (MessagePushBody body : bodies) {
            if (body.getId() == null) {
                body.setMessageId(mp.getId());
                pushBodyMapper.save(body);
            } else {
                body.setUpdateTime(new Date());
                pushBodyMapper.update(body);
            }
        }
        if (deleteBodyIds != null) {
            for (Long id : deleteBodyIds) {
                MessagePushBody body = this.pushBodyMapper.getById(id);
                if (body != null) {
                    body.setStatus(1);
                    body.setUpdateTime(new Date());
                    this.pushBodyMapper.update(body);
                }
            }
        }
    }

    private Map<String, Object> push(Long id, String creator, boolean job) {
        Map<String, Object> resultMap = Maps.newHashMap();
        resultMap.put("success", true);
        MessagePush mp = null;
        IDistLock lock = distLockManager.buildRedDistLock(MESSAGE_MODEL_ID_KEY + id);
        try {
            try {
                if (lock.tryLock(20, -1, TimeUnit.SECONDS)) {
                    mp = pushMapper.getById(id);
                    if (mp == null) {
                        log.info("消息推送，主体[ID:{}]不存在数据", id);
                        resultMap.put("success", false);
                        resultMap.put("msg", "记录不存在");
                        return resultMap;
                    }
                    if (mp.getStatus() != 2) {
                        log.info("消息推送，主体[ID:{}]要发送的记录状态不是未发送", id);
                        resultMap.put("success", false);
                        resultMap.put("msg", "发送的记录状态不是未发送状态");
                        return resultMap;
                    }
                    if (StringUtils.equals(mp.getCreator(), creator)) {
                        log.info("消息推送，主体[ID:{},adminId:{}]自己创建的自己不能推送哦", id, creator);
                        resultMap.put("success", false);
                        resultMap.put("msg", "自己创建的自己不能推送哦");
                        return resultMap;
                    }
                } else {
                    log.error("加锁获取消息对象失败：{}", id);
                    resultMap.put("success", false);
                    resultMap.put("msg", "对记录进行加锁失败，请稍后重试");
                    return resultMap;
                }
            } catch (InterruptedException e) {
                log.error("对数据{}加锁失败：{}", id, e);
                throw new RuntimeException(e);
            }
            org.slf4j.Logger log = job ? this.logger : MessagePushServiceImpl.log;
            log.info("消息推送，开始构建推送对象[{}]", mp);

            List<MessagePushBody> pushBodies = this.pushBodyMapper.selectByMessageId(mp.getId());
            String channel = mp.getChannel();
            List<String> excludeLanguages = Lists.newArrayList();// 存储明确指定的语言
            MultipleNotificationPacket enPacket = null; // 代表英文信息对象
            List<MultipleNotificationPacket> packets = new ArrayList<>();
            for (MessagePushBody pushBody : pushBodies) {
                String language = "locale_" + pushBody.getLanguage();
                excludeLanguages.add(language);

                MultipleNotificationPacket packet = new MultipleNotificationPacket();
                PushCommand command = new PushCommand();
                if (StringUtils.isNotBlank(mp.getUsers())) {
                    List<String> userIds = Arrays.asList(StringUtils.split(mp.getUsers(), ","));
                    command.getUsers().addAll(userIds);
                }
                command.setTimeToLive(mp.getHoldonHours() == null ? 0 : mp.getHoldonHours() * 3600);
                command.setTags(Arrays.asList(language));
                command.setTagNotList(Arrays.asList("NS", "AS"));
                packet.setCommand(command);
                if (channel.indexOf("a") != -1) {
                    AppPayload android = this.createAppPayload(mp, pushBody, new AndroidPayload());
                    packet.setAndroidMessage((AndroidPayload) android);
                }
                if (channel.indexOf("b") != -1) {
                    AppPayload ios = this.createAppPayload(mp, pushBody, new IosPayload());
                    packet.setIosMessage((IosPayload) ios);
                }
                if (channel.indexOf("c") != -1) {
                    PcPayload pc = this.createPcPayload(mp, pushBody);
                    packet.setPcMessage(pc);
                }
                if (channel.indexOf("d") != -1) {
                    WebPayload web = this.createWebPayload(mp, pushBody);
                    packet.setWebMessage(web);
                }
                if (packet.getAndroidMessage() != null || packet.getIosMessage() != null
                        || packet.getPcMessage() != null || packet.getWebMessage() != null) {
                    if (StringUtils.equalsIgnoreCase(pushBody.getLanguage(), "en")) {
                        enPacket = packet;
                    } else {
                        packets.add(packet);
                    }
                }
            }
            Set<String> allLanguage = null;
            try {
                allLanguage = deviceService.languageTags();
            } catch (Exception e) {
                log.warn("消息推送，主体[{}]获取语言失败:{}", mp.getId(), e);
                resultMap.put("success", false);
                resultMap.put("msg", "获取语言出现错误");
                return resultMap;
            }
            // 如果还有没有明确指定的语言，则将其和英文语言信息合并
            if (allLanguage.size() > excludeLanguages.size()) {
                List<String> otherLanguages = Lists.newArrayList();
                for (String key : allLanguage) {
                    String language = "locale_" + key;
                    if (!excludeLanguages.contains(language)) {
                        otherLanguages.add(language);
                    }
                }
                otherLanguages.add("locale_en");
                List<List<String>> otherLanguagesList = Lists.partition(otherLanguages, 20);
                for (List<String> list : otherLanguagesList) {
                    MultipleNotificationPacket clonePacket = SerializationUtils.clone(enPacket);
                    clonePacket.getCommand().setTags(list);
                    packets.add(clonePacket);
                }
            } else {
                packets.add(enPacket);
            }
            if (packets.size() > 0) {
                String[] result = new String[1];
                this.push.sendMultiple(packets, new Callback(result));
                log.info("推送管理消息成功推送到极光服务器，返回信息是：{}", result[0]);
                mp.setStatus(3);
                mp.setSendTime(new Date());
                pushMapper.update(mp);
                resultMap.put("success", true);
                // if (StringUtils.isBlank(result[0])) {
                // mp.setStatus(3);
                // mp.setSendTime(new Date());
                // pushMapper.update(mp);
                // log.info("消息推送，主体[{}]推送成功", mp.getId());
                // return true;
                // } else {
                // log.warn("消息推送，主体[{}]推送失败：{}", mp.getId(), result[0]);
                // return false;
                // }
            }
        } catch (Exception e) {
            log.warn("推送失败，异常是：", e);
            resultMap.put("success", false);
            resultMap.put("msg", "推送失败");
            return resultMap;
        } finally {
            lock.unlock();
        }
        return resultMap;
    }

    // private boolean startScheduleForSend(MessagePush messagePushModel) {
    // if ("fixed".equals(messagePushModel.getPushType())) {
    // this.removeSendSchedule(messagePushModel.getId());
    // long time = messagePushModel.getSendTime().getTime();
    // Date nowDate = utcNow();
    // long now = nowDate.getTime();
    // long delay = time - now;
    // log.info("消息推送，[{}]将在{}秒后触发推送动作", messagePushModel, delay / 1000);
    // ScheduledFuture<?> future = scheduleService.schedule(() -> {
    // MessagePush model = pushMapper.getById(messagePushModel.getId());
    // if (model != null) {
    // log.info("消息推送，定时推送任务开始执行[{}]", model.getId());
    // if (model.getStatus() == 1) {
    // log.info("消息推送，定时推送任务执行中[{}]，发现状态是{}，因此作废。", model.getId(), model.getStatus());
    // model.setStatus(4);
    // pushMapper.update(model);
    // }
    // if (model.getStatus() != 2) {
    // log.info("消息推送，定时推送任务执行中[{}]，发现状态{}不是未发送，因此将不做任何动作。", model.getId(), model.getStatus());
    // }
    // push(model);
    // }
    // futures.remove(model.getId());
    // }, delay, TimeUnit.MILLISECONDS);
    // futures.put(messagePushModel.getId(), future);
    // return true;
    // }
    // return false;
    // }

    // private void removeSendSchedule(Long id) {
    // ScheduledFuture<?> future = this.futures.get(id);
    // if (future != null) {
    // future.cancel(true);
    // this.futures.remove(id);
    // }
    // }

    private Date utcNow() {
        Date nowDate = null;
        TimeZone tz = TimeZone.getDefault();
        if (tz.getID().equals("UTC")) {
            nowDate = new Date();
        } else {
            int diffTime = TimeZone.getDefault().getRawOffset() - TimeZone.getTimeZone("UTC").getRawOffset();
            nowDate = new Date(new Date().getTime() - diffTime);
        }
        return nowDate;
    }

    private AppPayload createAppPayload(MessagePush mp, MessagePushBody pushBody, AppPayload app) {
        app.setTitle(pushBody.getTitle());
        app.setContent(pushBody.getContent());
        app.setBusType("AS");
        if ("open".equals(mp.getAppActivity())) {
            app.setAction(0);
        } else if ("openAppIn".equals(mp.getAppActivity())) {
            app.setAction(1);
            String intent = mp.getOpenAppInUrl();
            String params = mp.getOpenAppInUrlParams();
            if (StringUtils.isNotBlank(params)) {
                intent += "?" + params;
            }
            app.setIntent(intent);
        } else {
            app.setAction(2);
            if (StringUtils.equalsIgnoreCase(pushBody.getLanguage(), "cn")) {
                app.setWeb(mp.getOpenAppLinkCn());
            } else {
                app.setWeb(mp.getOpenAppLinkEn());
            }
        }
        return app;
    }

    private PcPayload createPcPayload(MessagePush mp, MessagePushBody pushBody) {
        PcPayload pc = new PcPayload();
        pc.setTitle(pushBody.getTitle());
        pc.setContent(pushBody.getContent());
        pc.setBusType("AS");
        if ("open".equals(mp.getPcActivity())) {
            pc.setAction(0);
        } else if ("openPcLink".equals(mp.getPcActivity())) {
            pc.setAction(1);
            if (StringUtils.equalsIgnoreCase(pushBody.getLanguage(), "cn")) {
                pc.setWeb(mp.getOpenPcWebCn());
            } else {
                pc.setWeb(mp.getOpenPcWebEn());
            }
        } else {
            pc.setAction(2);
            String intent = mp.getOpenPcAppUrl();
            String appPageParam = mp.getOpenPcAppUrlParams();
            if (StringUtils.isNotBlank(appPageParam)) {
                intent += "?" + appPageParam;
            }
            pc.setIntent(intent);
        }
        return pc;
    }

    private WebPayload createWebPayload(MessagePush mp, MessagePushBody pushBody) {
        WebPayload web = new WebPayload();
        web.setTitle(pushBody.getTitle());
        web.setContent(pushBody.getContent());
        web.setBusType("AS");
        if ("open".equals(mp.getWebActivity())) {
            web.setAction(0);
        } else {
            web.setAction(1);
            if (StringUtils.equalsIgnoreCase(pushBody.getLanguage(), "cn")) {
                web.setWeb(mp.getOpenWebUrlCn());
            } else {
                web.setWeb(mp.getOpenWebUrlEn());
            }

        }
        return web;
    }
}
